<style>
.notefield{
  width: 100%;
  resize: none;
  font-size: 18px;
  height: 50px;
  border-radius: 3px;
  padding: 5px;
  margin: 10px 0px;
}
.blankmessage{
  font-style: italic;
}
.note-content{
  border: 1px dashed black;
  border-radius: 5px;
  width: 100%;
  padding: 5px;
  padding-top: 25px;
  word-wrap: break-word;
}
.email__alert{
  display: none;
  margin: 0;
}
.panel-right-elements{
  float: right;
}
.email__container{
  border: 1px solid gray;
  margin: 10px;
  padding-left: 50px;
  padding-top: 5px;
}
.to__subject{
  margin: 5px;
  font-size: 20px;
  color: black;
  text-align: center;
}
.time__badge{
  float: right;
  margin-top: 7px;
  margin-right: 7px;
}
.single__note{
  width: 60%;
}
</style>
<div class="panel-group" id="accordion-<%= feedback_message.id %>" role="tablist" aria-multiselectable="true">
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="heading<%= feedback_message.id %>">
      <h2 class="panel-title">
        <a href="#collapse<%= feedback_message.id %>" role="button" data-toggle="collapse" data-parent="#accordion" aria-expanded="true" aria-controls="collapse<%= feedback_message.id %>">
          Report #<%= feedback_message.id %> - Submitted: <%= time_ago_in_words feedback_message.created_at %> ago
        </a>
        <div class="panel-right-elements">
          ✉️ Emails Sent: <%= feedback_message.email_messages.count %> |
          <a href="/internal/reports/<%= feedback_message.id %>">Link to Report #<%= feedback_message.id %></a>
        </div>
      </h2>
    </div>
    <div class="panel-collapse collapse in" id="collapse<%= feedback_message.id %>" role="tabpanel" aria-labelledby="heading<%= %>">
      <div class="panel-body">
      <h2>
        Reporter:
        <% if feedback_message.reporter_id? %>
          <%= feedback_message.reporter.name %>
          <a href="<%= feedback_message.reporter.path %>">@<%= feedback_message.reporter.username %></a>
        <% else %>
          Anonymous
        <% end %>
      </h2>
      <h3>
        Reported URL (new tab):
        <br>
        <a href="<%= feedback_message.reported_url %>" target="_blank"><%= feedback_message.reported_url %></a>
      </h3>
      <h3>Category: <%= feedback_message.category %></h3>
      <h3>
        Message:
      </h3>
      <p>
        <% if feedback_message.message.blank? %>
          <span class="blankmessage">No message was left.</span>
        <% else %>
          <%= feedback_message.message %>
        <% end %>
      </p>
      <h3>
        Status:  <%= f.select :status, ['Open', 'Invalid', 'Resolved'], {}, id: "status__#{feedback_message.id}" %>
        <button class="btn btn-primary" role="button" id="save__status__<%= feedback_message.id %>">SAVE STATUS</button>
      </h3>
    <hr>
      <h3>Previous Emails:</h3>
      <div class="previous__emails__container">
        <% EmailMessage.where(feedback_message_id: feedback_message.id).each do |email| %>
        <div class="email__container">
          <p class="to__subject">Type: <%= email.utm_campaign.capitalize %></p>
          <p class="to__subject">To: <%= email.to %></p>
          <p class="to__subject">Subject: <%= email.subject %></p>
          <%= email.body_html_content.html_safe %>
        </div>
        <% end %>
      </div>
      <h3>Email Form:</h3>
      <ul class="nav nav-tabs" role="tablist">
        <li role="presentation" class="active"><a href="#reporter-<%= feedback_message.id %>" aria-controls="reporter-<%= feedback_message.id %>" role="tab" data-toggle="tab">Reporter</a></li>
        <li role="presentation"><a href="#offender-<%= feedback_message.id %>" aria-controls="offender-<%= feedback_message.id %>" role="tab" data-toggle="tab">Offender</a></li>
        <li role="presentation"><a href="#victim-<%= feedback_message.id %>" aria-controls="victim-<%= feedback_message.id %>" role="tab" data-toggle="tab">Victim</a></li>
      </ul>

      <div class="tab-content">
        <div role="tabpanel" class="tab-pane fade in active" data-id="<%= feedback_message.id %>" data-userType="reporter" id="reporter-<%= feedback_message.id %>">
          <h3>
            Send to:
            <br>
            <%= email_field_tag :reporter_email_to, feedback_message.reporter&.email, class: "form-control", id: "reporter__emailto__#{feedback_message.id}", required: true %>
          </h3>
          <h3>Subject:</h3>
            <%= text_field_tag :reporter_email_subject, reporter_email_details[:subject], class: "form-control", id: "reporter__subject__#{feedback_message.id}" %>
          <h3>Body:</h3>
          <%= text_area_tag (:reporter_email_body), reporter_email_details[:body], class: "form-control", style: "height: 300px;", id: "reporter__body__#{feedback_message.id}" %>
        </div>
        <div role="tabpanel" class="tab-pane fade" data-id="<%= feedback_message.id %>" data-userType="offender" id="offender-<%= feedback_message.id %>">
          <h3>
            Send to:
            <br>
            <%= email_field_tag :offender_email_to, feedback_message.offender&.email, class: "form-control", id: "offender__emailto__#{feedback_message.id}", required: true %>
          </h3>
          <h3>Subject:</h3>
            <%= text_field_tag :offender_email_subject, offender_email_details[:subject], class: "form-control", id: "offender__subject__#{feedback_message.id}" %>
          <h3>Body:</h3>
            <%= text_area_tag (:offender_email_body), offender_email_details[:body], class: "form-control", style: "height: 300px;", id: "offender__body__#{feedback_message.id}" %>
        </div>
        <div role="tabpanel" class="tab-pane fade" data-id="<%= feedback_message.id %>" data-userType="victim" id="victim-<%= feedback_message.id %>">
          <h3>
            Send to:
            <br>
            <%= email_field_tag :victim_email_to, feedback_message.victim&.email, class: "form-control", id: "victim__emailto__#{feedback_message.id}", required: true %>
          </h3>
          <h3>Subject:</h3>
            <%= text_field_tag :victim_email_subject, victim_email_details[:subject], class: "form-control", id: "victim__subject__#{feedback_message.id}" %>
          <h3>Body:</h3>
            <%= text_area_tag (:victim_email_body), victim_email_details[:body], class: "form-control", style: "height: 300px;", id: "victim__body__#{feedback_message.id}" %>
        </div>
      </div>

      <br>
      <button class="btn btn-primary" type="submit" id="send__email__btn__<%= feedback_message.id %>">SEND EMAIL ✉️ </button>
      <div class="email__alert alert fade in" id="email__alert__<%= feedback_message.id %>">
      </div>

      <h3>Notes:</h3>
      <div class="notes__container" id="notes__<%= feedback_message.id %>">
        <% feedback_message.notes&.order("created_at").each do |note| %>
          <div class="single__note">
            <span class="badge time__badge">
              <%= time_ago_in_words note.created_at %> ago
            </span>
            <p class="note-content">
              <%= note.author.name %>: <%= note.content %>
            </p>
          </div>
        <% end %>
      </div>
      <input type="hidden" name="reason" value="<%= feedback_message.feedback_type %>" id="note__reason__<%= feedback_message.id %>">
      <input type="hidden" name="noteable_id" value="<%= feedback_message.id %>" id="note__noteable-id__<%= feedback_message.id %>">
      <input type="hidden" name="noteable_type" value="FeedbackMessage" id="note__noteable-type__<%= feedback_message.id %>">
      <input type="hidden" name="author_id" value="<%= current_user.id %>" id="note__author-id__<%= feedback_message.id %>">
      <input
        type="textarea"
        name="content"
        placeholder="Leave some notes about the status and context of this report."
        class="notefield"
        id="note__content__<%= feedback_message.id %>"
        required
      >
      <br>
    <button class="btn btn-primary" type="submit" id="note__submit__<%= feedback_message.id %>">SUBMIT NOTE 📝 </button>

      </div>
    </div>
  </div>
</div>

<script>
  function saveStatus(id) {
    var formData = new FormData();
    var statusSelectTag = document.getElementById('status__' + id);
    var statusBtn = document.getElementById('save__status__' + id);
    formData.append('id', id);
    formData.append('status', statusSelectTag.options[statusSelectTag.selectedIndex].value);

    fetch('/internal/reports/save_status', {
      method: 'POST',
      headers: {
        'X-CSRF-Token': document.querySelector("meta[name='csrf-token']").content,
      },
      body: formData,
      credentials: 'same-origin'
    })
    .then(response => response.json()
      .then(json => {
        if (json.outcome === 'Success') {
        console.log(json.outcome)
          statusBtn.innerText = "Saved!";
          setTimeout(function() {
            statusBtn.innerText = "SAVE STATUS"
          }, 1000);
        } else {
        }
      }))
  }

  document.getElementById('save__status__' + <%= feedback_message.id %>).addEventListener('click', function(event) {
    event.preventDefault();
    var reportId = <%= feedback_message.id %>
    saveStatus(reportId);
  });

  function successfulEmail(alert) {
    alert.style.display = 'inline-block';
    alert.classList.add('alert-success');
    alert.innerHTML = "Email sent successfully! Refresh to see";
  }

  function failedEmail(alert) {
    alert.style.display = 'inline-block';
    alert.classList.add('alert-danger');
    alert.innerHTML = "Email failed to send, see console for errors";
  }

  function sendEmail(id) {
    var activeTab = document.querySelector(".tab-pane.fade.in.active[data-id='" + id + "']");
    var alert = document.getElementById('email__alert__' + id);
    var sendEmailBtn = document.getElementById('send__email__btn__' + id);
    var userType = activeTab.dataset.usertype;
    var emailToAddress = activeTab.querySelector("#" + userType + "__emailto__" + id).value;
    var subjectLine = activeTab.querySelector("#" + userType + "__subject__" + id).value;
    var emailBody = activeTab.querySelector("#" + userType + "__body__" + id).value;

    alert.style.display = "none";
    alert.classList.remove("alert-warning");
    alert.classList.remove("alert-success");
    alert.classList.remove("alert-danger");

    if(emailToAddress === "") {
      alert.style.display = 'inline-block';
      alert.classList.add("alert-warning");
      alert.innerHTML = "Email can't be blank!"
      return
    }

    if(emailBody.includes("[*") || emailBody.includes("*]")) {
      alert.style.display = 'inline-block';
      alert.classList.add("alert-warning");
      alert.innerHTML = "Username or (comment/post) wasn't changed!"
      return
    }

    var formData = new FormData();
    formData.append('feedback_message_id', id);
    formData.append('email_to', emailToAddress);
    formData.append('email_body', emailBody);
    formData.append('email_subject', subjectLine);
    formData.append('email_type', userType);

    fetch('/internal/reports/send_email', {
      method: 'POST',
      headers: {
        'X-CSRF-Token': document.querySelector("meta[name='csrf-token']").content,
      },
      body: formData,
      credentials: 'same-origin'
    })
    .then(response => response.json()
      .then(json => {
        if (json.outcome === "Success") {
          successfulEmail(alert);
        } else {
          console.log('email failed')
          failedEmail(alert);
        }
      }))
    .catch(error => {
      failedEmail(alert);
      console.log(error);
    })
  }

  document.getElementById('send__email__btn__' + <%= feedback_message.id %>).addEventListener('click', function(event) {
    event.preventDefault();
    var reportId = <%= feedback_message.id %>;
    sendEmail(reportId);
  });

  function addNoteToPage(noteParams, id) {
    var notesDiv = document.getElementById('notes__' + id);

    var singleNoteDiv = document.createElement('div');
    singleNoteDiv.setAttribute('class', 'single__note');

    var timeBadge = document.createElement('span');
    timeBadge.setAttribute('class', 'time__badge badge');
    timeBadge.innerText = "just now";
    singleNoteDiv.append(timeBadge);

    var newNote = document.createElement('p');
    newNote.className = 'note-content';
    var noteContent = document.createTextNode(noteParams.author_name + ': ' + noteParams.content);
    newNote.appendChild(noteContent);
    singleNoteDiv.append(newNote);

    notesDiv.append(singleNoteDiv);
  }

  function clearNote(id) {
    document.getElementById('note__content__' + id).value = '';
  }

  function submitNote(id) {
    var formData = new FormData();
    formData.append('content', document.getElementById('note__content__' + id).value)
    formData.append('reason', document.getElementById('note__reason__' + id).value)
    formData.append('noteable_id', document.getElementById('note__noteable-id__' + id).value)
    formData.append('noteable_type', document.getElementById('note__noteable-type__' + id).value)
    formData.append('author_id', document.getElementById('note__author-id__' + id).value)

    fetch('/internal/reports/create_note', {
      method: 'POST',
      headers: {
        'X-CSRF-Token': document.querySelector("meta[name='csrf-token']").content,
      },
      body: formData,
      credentials: 'same-origin'
    })
    .then(response => response.json()
      .then(json => {
        if (json.outcome === 'Success') {
          addNoteToPage(json, id);
          clearNote(id);
        } else {
          // failedNote();
        }
      })
    .catch(error => {
      // failedNote();
      console.log(error);
    }))
  }

  document.getElementById('note__submit__<%= feedback_message.id %>').addEventListener('click', function() {
    var reportId = <%= feedback_message.id %>;
    submitNote(reportId);
  });
</script>
